/**
 * 转正设置
 */
import React from 'react';
import { Table, Button, Popconfirm, Spin, message, Divider, Icon as AntdIcon } from 'antd';
import { history } from 'umi'
import authHelper from '@/utils/auth/helper';
import { DividerContainer, Icon, EllipsisTooltip } from '@/molecules';
import { useRequest, defaultFormatResult } from '@/hooks';
import { newTabProps } from '@/utils/tab';
import { fetchCompany } from '@/containers/service';
import { getRuleList, deleteRule } from './services';
import EvaluationTable from './EvaluationTable';
import styles from './index.less';

const { checkCode } = authHelper;

const Informal = () => {
    const { data: companyList, loading: companyLoading } = useRequest(
        () =>
            fetchCompany({
                organizationPermissions: 0,
                showTreeFlag: 0
            }),
        { cacheKey: 'companyList', ...defaultFormatResult }
    );

    const { data, loading, run: fetchRuleList } = useRequest(getRuleList, {
        manual: true,
        ...defaultFormatResult
    });

    // 删除设置
    const { loading: delLoading, run: delRule } = useRequest(deleteRule, {
        manual: true,
        onSuccess: res => {
            const { code, msg } = res;
            if (code === 10000) {
                fetchRuleList();
                message.success('操作成功');
                return;
            }
            message.error(msg);
        }
    });

    React.useEffect(() => {
        fetchRuleList();
    }, []);

    const getPopupContainer = trigger => {
        if (trigger?.parentElement?.parentElement?.parentElement) {
            return trigger?.parentElement?.parentElement?.parentElement;
        }
        return document.body;
    };

    const renderCompanyNames = (text, record) => {
        if (record?.common === 1) {
            return '全集团';
        }
        if (text && text.length > 0) {
            const names = text.map(item => companyList?.find(it => it.organizationCode === item)?.organizationName);
            if (names.filter(it => it).length === 0) {
                return '';
            }
            return (
                <EllipsisTooltip
                    style={{ marginBottom: 0 }}
                    tooltipProps={{
                        getPopupContainer
                    }}
                >
                    {names.join('、')}
                </EllipsisTooltip>
            );
        }
        return '--';
    };

    const renderToolTip = (text, tooltipProps) =>
        text ? (
            <EllipsisTooltip tooltipProps={tooltipProps} style={{ marginBottom: 0 }}>
                {text}
            </EllipsisTooltip>
        ) : (
            '--'
        );

    const columns = [
        {
            title: '转正规则名称',
            dataIndex: 'chName',
            render: (text, record) => (
                <div style={{ display: 'flex' }}>
                    {renderToolTip(text, {
                        placement: 'topLeft',
                        getPopupContainer
                    })}
                    {record?.common === 1 && (
                        <div
                            style={{
                                flexShrink: 0,
                                width: 32,
                                height: 20,
                                margin: '2px 0 2px 8px',
                                textAlign: 'center',
                                lineHeight: '20px',
                                fontSize: 10,
                                color: 'rgba(0,0,0,0.45)',
                                borderRadius: 3,
                                background: 'rgba(0, 0, 0, 0.05)'
                            }}
                        >
                            默认
                        </div>
                    )}
                </div>
            )
        },
        {
            title: '规则介绍',
            dataIndex: 'chIntroduce',
            width: '25%',
            render: text =>
                renderToolTip(text, {
                    getPopupContainer
                })
        },
        {
            title: '适用行政机构',
            dataIndex: 'companyCodeList',
            render: renderCompanyNames
        },
        {
            title: '操作',
            dataIndex: 'action',
            width: 150,
            className: styles.tableAction,
            onCell: () => ({
                onClick: e => {
                    e.stopPropagation();
                }
            }),
            render: (text, record) => (
                <DividerContainer>
                    {checkCode('office:turnover:setting:informal:edit') && (
                        <Icon
                            title="编辑"
                            type="listfunction_edit_icon_default"
                            onClick={() => {
                                history.push({
                                    pathname: '/office/personnelManagement/onboardAndLeave/setting/informal/edit',
                                    query: { id: record.id }
                                });
                            }}
                        />
                    )}
                    {checkCode('office:turnover:setting:informal:add') && (
                        <Icon
                            title="复制"
                            type="copy_o"
                            onClick={() => {
                                history.push({
                                    pathname: '/office/personnelManagement/onboardAndLeave/setting/informal/add',
                                    query: { id: record.id }
                                });
                            }}
                        />
                    )}
                    {checkCode('office:turnover:setting:informal:delete') && record?.common !== 1 && (
                        <Popconfirm
                            title="确定删除该规则吗?"
                            onConfirm={() => delRule(record?.id)}
                            okText="确定"
                            cancelText="取消"
                        >
                            <Icon title="删除" type="listfunction_delete_icon_default" />
                        </Popconfirm>
                    )}
                </DividerContainer>
            )
        }
    ];

    const handleAdd = () => {
        history.push({
            pathname: '/office/personnelManagement/onboardAndLeave/setting/informal/add'
        });
    };

    return (
        <Spin spinning={loading || delLoading || companyLoading}>
            {/* {checkCode('office:turnover:setting:informal:add') && (
                <Row type="flex" justify="end">
                    <Button type="primary" style={{ margin: '0 0 16px' }} onClick={handleAdd}>
                        新增规则
                    </Button>
                </Row>
            )} */}
            <h2>转正规则</h2>
            <Table
                className={styles.fixedAction}
                rowClassName={styles.tableRow}
                rowKey="id"
                columns={columns}
                dataSource={data || []}
                pagination={false}
                scroll={{ x: 1000 }}
                onRow={record => ({
                    onClick: () => {
                        history.push({
                            pathname: '/office/personnelManagement/onboardAndLeave/setting/informal/detail',
                            query: { id: record.id },
                            ...newTabProps
                        });
                    }
                })}
            />
            {checkCode('office:turnover:setting:informal:add') && (
                <Button block type="dashed" style={{ marginTop: 12 }} onClick={handleAdd}>
                    <AntdIcon type="plus" /> 添加
                </Button>
            )}
            <Divider />
            <EvaluationTable />
        </Spin>
    );
};

export default Informal;
